package ch.sv7.tool.dbmanager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

/**
 *
 * @author svt
 *
 */
public class StringUtil {

	public static String sortCommaSeparated(String commaSeparated) {
		List values = new ArrayList();
		StringTokenizer tokens = new StringTokenizer(commaSeparated, ",");
		while (tokens.hasMoreTokens()){
			String value = tokens.nextToken().trim();
			values.add(value);
		}
		Collections.sort(values);
		StringBuffer result = new StringBuffer();
		for (int i=0; i< values.size(); i++) {
			String value = (String)values.get(i);
			if (result.length() > 0) {
				result.append(", ");
			}
			result.append(value);
		}
		return result.toString();
	}
	
	public static List commaSeparatedToList(String commaSeparated){
		List values = new ArrayList();
		StringTokenizer tokens = new StringTokenizer(commaSeparated, ",");
		while (tokens.hasMoreTokens()){
			String value = tokens.nextToken().trim();
			values.add(value);
		}
		return values;
	}
	
	public static Set commaSeparatedToSet(String commaSeparated){
		Set values = new HashSet();
		StringTokenizer tokens = new StringTokenizer(commaSeparated, ",");
		while (tokens.hasMoreTokens()){
			String value = tokens.nextToken().trim();
			values.add(value);
		}
		return values;
	}
	
	public static String[] commaSeparatedToArray(String commaSeparated){
		return (String[])commaSeparatedToList(commaSeparated).toArray(new String[]{});
	}
	
	public static String listToCommaSeparated(List values) {
		StringBuffer buffer = new StringBuffer();
		if (values != null && values.size() > 0) {
			for (int i=0; i< values.size(); i++) {
				String value = values.get(i).toString();
				if (i > 0){
					buffer.append(", ");
				}
				buffer.append(value);
			}
		}
		return buffer.toString();
	}
	
	public static boolean safeEquals(String str1, String str2) {
		if (str1 == null && str2 == null){
			return true;
		} else if (str1 != null && str2 != null){
			return str1.equals(str2);
		} else {
			return false;
		}
	}
}
